package com.tb.market;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.tb.coremodel.viewmodel.MarketViewModel;

import com.tb.common.base.ARouterPath;
import com.tb.common.base.BaseFragment;
import com.tb.coremodel.datamodel.http.entities.MarketData;
import com.tb.coremodel.viewmodel.ViewModelProviders;
import com.tb.market.databinding.FragmentMarketBinding;


/**
 * @Desc Created by Clark on 2022/02/28.
 */
@Route(path = ARouterPath.MarketListFgt)
public class FragmentMarket extends BaseFragment {

    FragmentMarketBinding marketBinding;

    MarketAdapter marketAdapter;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ARouter.getInstance().inject(FragmentMarket.this);
        marketBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_market,container,false);

        marketAdapter = new MarketAdapter(marketItemClickCallback);
        marketBinding.setRecyclerAdapter(marketAdapter);
        final MarketViewModel marketViewModel =
                ViewModelProviders.of(FragmentMarket.this).get(MarketViewModel.class);

        subscribeToModel(marketViewModel);

        return marketBinding.getRoot();
    }


    MarketItemClickCallback marketItemClickCallback = new MarketItemClickCallback() {
        @Override
        public void onClick(MarketData.ResultsBean fuliItem) {
            Toast.makeText(getContext(), fuliItem.getDesc(), Toast.LENGTH_SHORT).show();
        }
    };
    /**
     * 订阅数据变化来刷新UI
     * @param model
     */
    private void subscribeToModel(final MarketViewModel model){
        //观察数据变化来刷新UI
        model.getLiveObservableData().observe(getViewLifecycleOwner(), new Observer<MarketData>() {
            @Override
            public void onChanged(@Nullable MarketData marketData) {
                Log.i("clark", "subscribeToModel onChanged onChanged");
                model.setUiObservableData(marketData);
                marketAdapter.setMarketList(marketData.getResults());
            }
        });
    }

}
